package com.hxt.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;

import com.google.common.collect.Maps;
import com.mongodb.annotations.ThreadSafe;

public class YmlUtil {

	/**
	 * key:文件名索引 value:配置文件内容
	 */
	private static Map<String, LinkedHashMap> ymls = Maps.newHashMap();

	/**
	 * string:当前线程需要查询的文件名
	 */
	private static ThreadLocal<String> nowFileName = new ThreadLocal<>();

	/**
	 * 加载配置文件
	 * 
	 * @param fileName
	 */
	public static void loadYml(String fileName) {
		nowFileName.set(fileName);
		if (!ymls.containsKey(fileName)) {
			ymls.put(fileName,
					new Yaml().loadAs(YmlUtil.class.getResourceAsStream("/" + fileName), LinkedHashMap.class));
		}
	}

	public static String getValue(String key) {
		// 首先将key进行拆分
		String[] keys = key.split("[.]");

		// 将配置文件进行复制
		Map ymlInfo = (Map) ymls.get(nowFileName.get()).clone();
		for (int i = 0; i < keys.length; i++) {
			Object value = ymlInfo.get(keys[i]);
			if (i < keys.length - 1) {
				ymlInfo = (Map) value;
			} else if (value == null) {
//				throw new Exception("key不存在");
			} else {
				return value.toString();
			}
		}
		throw new RuntimeException("不可能到这里的...");
	}

	public static Object getValue(String fileName, String key) {
		// 首先加载配置文件
		loadYml(fileName);
		return getValue(key);
	}

//	jiaparts: 
//		#-------------数据源配置-------------
//		  db: 
//		    xt:
//		      unique-resource-name: xt
//		      xa-data-source-class-name: com.mysql.jdbc.jdbc2.optional.MysqlXADataSource
//		      min-pool-size: 10
//		      max-pool-size: 1200
//		      borrow-connection-timeout: 30
//		      test-query: select 1
//		      maintenance-interval: 60
//		      xa-properties: 
//		        url: jdbc:mysql://127.0.0.1:3306/zbak?characterEncoding=utf8&allowMultiQueries=true&useSSL=false
//		        user: root
//		        password: root

	public static void main(String[] args) throws Exception {
		System.out.println((getValue("application.yml", "jiaparts.db.xt.xa-properties.url")));
		System.out.println((getValue("application.yml", "jiaparts.db.xt.xa-properties.user")));
		System.out.println((getValue("application.yml", "jiaparts.db.xt.xa-properties.password")));
	}
}
